<template>
  <div class="mod-seckill-shopAuditing">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="searchForm"
        :class="$t('language') === 'language' ? 'en-search-form': 'zh-search-form'"
      >
        <div class="input-row">
          <el-form-item
            prop="shopName"
            :label="$t('prodList.shopName') + ':'"
          >
            <el-input
              v-model="searchForm.shopName"
              clearable
              :placeholder="$t('prodList.shopName')"
            />
          </el-form-item>
          <el-form-item
            prop="intro"
            :label="$t('shop.shopProfile') + ':'"
          >
            <el-input
              v-model="searchForm.intro"
              clearable
              :placeholder="$t('shop.shopProfile')"
            />
          </el-form-item>
          <!--(-1:已删除 0: 停业中 1:营业中 2:平台下线 3:上线待审核 4:开设商城申请中 5:开设商城申请待审核)-->
          <el-form-item
            prop="shopStatusList"
            :label="$t('shopProcess.shopStatus') + ':'"
          >
            <el-select
              v-model="searchForm.shopStatusList"
              clearable
              :placeholder="$t('shopProcess.shopStatus')"
            >
              <el-option
                :label="$t('shop.inOperation')"
                :value="1"
              />
              <el-option
                v-if="paySettlementType!==1"
                :label="$t('shop.stop')"
                :value="0"
              />
              <el-option
                :label="$t('shop.offlineViolation')"
                :value="2"
              />
              <el-option
                :label="$t('shop.offlinePendingReview')"
                :value="3"
              />
              <el-option
                v-if="paySettlementType===1"
                :label="$t('shopProcess.storeOpenPendingReview')"
                :value="5"
              />
              <el-option
                v-if="paySettlementType===1"
                :label="$t('allinpay.onlineAuditFailure')"
                :value="6"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="mobile"
            :label="$t('shop.contactTel') + ':'"
          >
            <el-input
              v-model="searchForm.mobile"
              maxlength="11"
              clearable
              :placeholder="$t('shop.contactTel')"
            />
          </el-form-item>
          <el-form-item
            prop="merchantMobile"
            :label="$t('shop.merchantMobile') + ':'"
          >
            <el-input
              v-model="searchForm.merchantMobile"
              maxlength="11"
              clearable
              :placeholder="$t('shop.merchantMobile')"
            />
          </el-form-item>
          <el-form-item
            prop="type"
            :label="$t('shop.shopType') + ':'"
          >
            <el-select
              v-model="searchForm.type"
              clearable
              :placeholder="$t('shop.shopType')"
            >
              <el-option
                :label="$t('shop.generalStore')"
                :value="0"
              />
              <el-option
                :label="$t('shop.preferredStores')"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <!-- 是否试用 -->
          <el-form-item
            prop="hasTry"
            label="是否试用:"
          >
            <el-select
              v-model="searchForm.hasTry"
              clearable
              placeholder="是否试用"
            >
              <el-option
                :label="$t('publics.yes')"
                :value="1"
              />
              <el-option
                :label="$t('publics.no')"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="mallVersion"
            label="商城版本"
          >
            <el-select
              v-model="searchForm.mallVersion"
              clearable
              placeholder="商城版本"
            >
              <el-option
                label="免费版"
                :value="1"
              />
              <el-option
                label="基础版"
                :value="2"
              />
              <el-option
                label="标准版"
                :value="3"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('order.applicationTime') + ':'"
          >
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              :range-separator="$t('date.tip')"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('product.search') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch()"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <el-checkbox
          v-model="selectAll"
          class="all-check-btn"
          @change="onSelectAll"
        >
          {{ $t('publics.selectAll') }}
        </el-checkbox>
        <div
          class="default-btn primary-btn"
          @click="insertShop()"
        >
          {{ $t('crud.addTitle') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="exportShop()"
        >
          {{ $t('formData.export') }}
        </div>
        <div
          v-if="isAuth('shop:shopAuditing:audit')"
          :class="[dataListSelections.length <= 0 ? 'disabled-btn' : '', 'default-btn']"
          @click.stop="shopTypeHandle()"
        >
          {{ $t('shop.shopType') }}
        </div>
      </div>
      <div class="table-con audit-shop-table">
        <el-table
          :key="tabValue"
          ref="auditShopRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @selection-change="onSelectSome"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            prop="shopName"
            :label="$t('prodList.shopName')"
            width="320"
          >
            <template #default="scope">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <img-show :src="scope.row.shopLogo" />
                </div>
                <span class="table-cell-text">{{ scope.row.shopName || '-' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="intro"
            :label="$t('shop.shopProfile')"
            width="280"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.intro || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="shopStatusList"
            :label="$t('shopProcess.shopStatus')"
            width="auto"
          >
            <template #default="scope">
              <span
                v-if="scope.row.shopStatus === -1"
                class="tag-text"
              >{{ $t('shop.deleted') }}</span>
              <span
                v-else-if="scope.row.shopStatus === 0"
                class="tag-text"
              >{{ $t('shop.stop') }}</span>
              <span
                v-else-if="scope.row.shopStatus === 1"
                class="tag-text"
              >{{ $t('shop.inOperation') }}</span>
              <span
                v-else-if="scope.row.shopStatus === 2"
                class="tag-text"
              >{{ $t('shop.offlineViolation') }}</span>
              <span
                v-else-if="scope.row.shopStatus === 3 || (scope.row.shopStatus === 5 && paySettlementType!==1)"
                class="tag-text"
              >{{ $t('shop.offlinePendingReview') }}</span>
              <span
                v-else-if="scope.row.shopStatus === 4"
                class="tag-text"
              >{{ $t('shopProcess.shopApplication') }}</span>
              <span
                v-else-if="paySettlementType===1 && scope.row.shopStatus === 5"
                class="tag-text"
              >{{ $t('shopProcess.storeOpenPendingReview') }}</span>
              <span
                v-if="paySettlementType===1 && scope.row.shopStatus === 6"
                size="small"
                type="danger"
              >{{ $t('allinpay.onlineAuditFailure') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            :label="$t('order.applicationTime')"
            width="150"
          />
          <el-table-column
            prop="mobile"
            :label="$t('shop.contactTel')"
            width="110"
          />
          <el-table-column
            prop="type"
            :label="$t('shop.shopType')"
            width="auto"
          >
            <template #default="scope">
              <span class="tag-text">{{ [$t('shop.generalStore'),$t('shop.preferredStores')][scope.row.type] }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="type"
            label="是否试用"
            width="100"
          >
            <template #default="scope">
              <span class="tag-text">{{ scope.row.hasTry == 1 ? '是' : '否' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="type"
            label="商城版本"
            width="100"
          >
            <template #default="scope">
              <span class="tag-text">{{
                scope.row.mallVersion == 1 ? '免费版' :
                scope.row.mallVersion == 2 ? '基础版' : '标准版'
              }}</span>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            fixed="right"
            :label="$t('publics.operating')"
            width="350"
          >
            <template #default="scope">
              <div class="">
                <!-- 跳转到商城 -->
                <div
                  class="default-btn text-btn"
                  @click="gotoShop(scope.row.shopId)"
                >
                  跳转到商城
                </div>
                <!-- 查看 -->
                <div
                  class="default-btn text-btn"
                  @click="auditHandle(scope.row.shopId, 0)"
                >
                  {{ $t('seckill.view') }}
                </div>
                <!-- 编辑 -->
                <div
                  class="default-btn text-btn"
                  @click="auditHandle(scope.row.shopId, 1)"
                >
                  {{ $t('coupon.edit') }}
                </div>
                <!-- 账号管理 -->
                <div
                  v-if="isAuth('shop:shopAuditing:audit')"
                  class="default-btn text-btn"
                  @click="shopAccountHandle(scope.row.shopId)"
                >
                  {{ $t('shop.accountManagement') }}
                </div>
                <!-- 下线商城 -->
                <div
                  v-if="isAuth('shop:shopAuditing:lowerShelfShop') && scope.row.shopStatus <= 1"
                  class="default-btn text-btn"
                  @click="offlineHandle(scope.row)"
                >
                  {{ $t('shop.offlineShop') }}
                </div>
                <!-- 下线管理 -->
                <div
                  v-if="(isAuth('shop:shopAuditing:lowerShelfShop') && scope.row.shopStatus > 1) && (paySettlementType!==1 || (paySettlementType===1 && scope.row.companyInfoProcessStatus!==0))"
                  class="default-btn text-btn"
                  @click="shopAuditHandle(scope.row.shopId)"
                >
                  {{
                    scope.row.shopStatus === 2 ?
                      $t('distributionProdLog.offlineManagement')
                      : $t('product.pendingReview')
                  }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <!-- 下架管理 -->
    <offline-manage
      v-if="offlineDialogVisible"
      ref="offlineDataRef"
      @refresh-data-list="refreshChange"
    />
    <!-- 账号管理 -->
    <ShopAccount
      v-if="shopAccountVisible"
      ref="shopAccountRef"
      @refresh-data-list="refreshChange"
    />
    <!-- 导出商城 -->
    <el-dialog
      v-model="exportShopVisible"
      :title="$t('shopProcess.exportShop')"
    >
      <el-radio
        v-model="exportRadio"
        label="1"
      >
        {{ $t('shopProcess.exportSearchShop') }}
      </el-radio>
      <el-radio
        v-model="exportRadio"
        label="2"
      >
        {{ $t('shopProcess.exportSelectShop') }}
      </el-radio>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="exportShopVisible = false"
          >
            {{ $t('coupon.cancel') }}
          </div>
          <div
            class="default-btn primary-btn"
            type="primary"
            @click="confirmExport"
          >
            {{ $t('coupon.confirm') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 商城类型 -->
    <ShopType
      v-if="shopTypeVisible"
      ref="shopTypeRef"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import offlineManage from '../shop-edit/shop-offline-manage/index.vue'
import ShopAccount from '../shop-account/index.vue'
import ShopType from '../shop-detail-update/index.vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils/index.js'

const router = useRouter()

defineProps({
  tabValue: {
    type: String,
    default: ''
  }
})

const searchForm = reactive({
  shopStatusList: undefined,
  shopName: undefined,
  intro: undefined,
  mobile: undefined,
  type: undefined,
  merchantMobile: undefined
}) // 搜索

const allinpayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})

onMounted(() => {
  getDataList()
})

let tempSearchForm = null // 保存上次点击查询的请求条件
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const dateRange = ref([])
let theParams = null // 保存上次点击查询的请求条件
const dataList = ref([])
const getDataList = (pageParam, newData = false) => {
  pageParam = pageParam || page
  if (newData || !tempSearchForm) {
    tempSearchForm = {
      current: pageParam.currentPage,
      size: pageParam.pageSize,
      beginTime: dateRange.value ? dateRange.value[0] : null, // 开始时间
      endTime: dateRange.value ? dateRange.value[1] : null // 结束时间
    }
    theParams = JSON.parse(JSON.stringify(searchForm))
    theParams.shopStatusList = (theParams.shopStatusList !== null && theParams.shopStatusList !== undefined && theParams.shopStatusList !== '') ? theParams.shopStatusList : [0, 1, 2, 3]
  } else {
    tempSearchForm.current = pageParam.currentPage
    tempSearchForm.size = pageParam.pageSize
  }

  http({
    url: http.adornUrl('/shop/shopAuditing/page'),
    method: 'get',
    params: http.adornParams(Object.assign(tempSearchForm, theParams))
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
    page.currentPage = data.current

    // 末尾页数据为空重新请求
    if (!dataList.value.length && page.currentPage > 1) {
      page.currentPage = 1
      getDataList()
    }
  })
}

/**
 * 查看 / 审核
 * @param id 商城id
 * @param type 0-查看 1-编辑
 */
const auditHandle = (id, type) => {
  if (type === 1) {
    router.push({
      path: '/platform/audit-shop/edit/index',
      query: {
        shopId: id
      }
    })
  } else {
    router.push({
      path: '/platform/audit-shop/detail/index',
      query: {
        shopId: id
      }
    })
  }
}

const shopAccountVisible = ref(false)
const shopAccountRef = ref(null)
// 账号管理
const shopAccountHandle = (id) => {
  shopAccountVisible.value = true
  nextTick(() => {
    shopAccountRef.value?.init(id)
  })
}

const dataListSelections = ref([])
const shopTypeVisible = ref(false)
const shopTypeRef = ref(null)
// 账号管理
const shopTypeHandle = (id) => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.shopId
  })
  if (!ids.length && !dataListSelections.value.length) {
    return
  }
  shopTypeVisible.value = true
  nextTick(() => {
    shopTypeRef.value?.init(ids)
  })
}

/**
 * 新增商城
 */
const insertShop = () => {
  router.push('/platform/shop-process/index')
}

const exportShopVisible = ref(false)
/**
 * 导出商城
 */
const exportShop = () => {
  exportShopVisible.value = true
}

const exportRadio = ref('1')
let isSubmit = false
/**
 * 确定导出
 */
const confirmExport = () => {
  if (exportRadio.value !== '1' && exportRadio.value !== '2') {
    ElMessage({
      message: $t('shop.exportRadioEmptyTips'),
      type: 'error',
      duration: 1500,
      onClose: () => {
        isSubmit = false
      }
    })
    return
  }
  if (isSubmit) {
    return
  }
  isSubmit = true
  // 准备参数
  let params = {}
  if (exportRadio.value === '1') {
    // 导出模式为按搜索条件导出
    if (page.total === 0) {
      ElMessage({
        message: $t('shop.exportShopSearchEmptyTips'),
        type: 'error',
        duration: 1500,
        onClose: () => {
          isSubmit = false
        }
      })
      return
    }
    // 赋值搜索参数
    params = JSON.parse(JSON.stringify(searchForm))
    params.shopStatusList = (params.shopStatusList !== null && params.shopStatusList !== undefined) ? params.shopStatusList : [0, 1, 2, 3]
    params.begintIME = dateRange.value ? dateRange.value[0] : null
    params.endTime = dateRange.value ? dateRange.value[1] : null
    params.shopIds = null
  } else {
    // 导出模式为按选中的商城导出
    if (dataListSelections.value.length === 0) {
      ElMessage({
        message: $t('shop.exportShopSelectEmptyTips'),
        type: 'error',
        duration: 1500,
        onClose: () => {
          isSubmit = false
        }
      })
      return
    }
    // 赋值选中的商城id
    params.shopIds = dataListSelections.value.map(item => {
      return item.shopId
    })
  }
  const loading = ElLoading.service({
    lock: true,
    target: '.mod-seckill-shopAuditing',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/shopDetail/exportShop'),
    method: 'get',
    params: http.adornParams(params),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('shop.comInfoSorXls')
    const elink = document.createElement('a')
    if ('download' in elink) {
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('shop.exportSuccess'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        isSubmit = false
        exportShopVisible.value = false
      }
    })
  }).catch(() => {
    loading.close()
    isSubmit = false
  })
}

// 下架商城
const offlineHandle = (row) => {
  // 确定对商城[' + row.shopName + ']进行下线操作？如是，请填写下线理由
  let tips = $t('shop.shopTip1')
  tips = tips.replace('SHOPNAME', row.shopName)
  ElMessageBox.prompt(tips, $t('text.tips'), {
    confirmButtonText: $t('coupon.confirm'),
    cancelButtonText: $t('coupon.cancel'),
    inputPattern: /\s\S+|S+\s|\S/, // 不能全为空格 空字符串
    inputErrorMessage: $t('seckill.offlineReasonTip'),
    inputValidator: (value) => {
      if (value.length > 100) {
        return $t('seckill.offlineReasonTip1')
      }
    }
  }).then((obj) => {
    http({
      url: http.adornUrl('/platform/shopDetail/offline'),
      method: 'post',
      data: http.adornData({
        handleId: row.shopId,
        offlineReason: obj.value || null
      })
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(page)
        }
      })
    })
  })
}

/**
 * 刷新回调
 */
const refreshChange = () => {
  getDataList(page)
}

// 清空自定义数据
const searchReset = () => {
  dateRange.value = []
}

const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

const selectAll = ref(false)
// 多选变化
const onSelectSome = (val) => {
  dataListSelections.value = val
  selectAll.value = val.length === dataList.value.length
}

// 弹窗处理
const shopAuditHandle = (id) => {
  getOfflineDetailByShopId(id)
}

const offlineDialogVisible = ref(false)
const offlineDataRef = ref(null)
/**
 * 获取最新商城下线事件
 */
const getOfflineDetailByShopId = (shopId) => {
  offlineDialogVisible.value = true
  http({
    url: http.adornUrl(`/platform/shopDetail/getOfflineHandleEventByShopId/${shopId}`),
    method: 'GET'
  }).then(({ data }) => {
    nextTick(() => {
      offlineDataRef.value?.init(data, paySettlementType.value === 1 ? 'canDirectOnline' : null)
    })
  })
}

const auditShopRef = ref(null)
/**
 * 全选按钮
 */
const onSelectAll = () => {
  selectAll.value = auditShopRef.value.selection?.length < dataList.value.length
  auditShopRef.value.toggleAllSelection()
}

const searchFormRef = ref(null)
/**
 * 重置表单
 */
const onResetSearch = () => {
  searchFormRef.value.resetFields()
  searchReset()
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}

const gotoShop = (shopId) => {
  const url = import.meta.env.VITE_APP_SHOP_ADDRESS
  window.open(`${url}shop-index?sid=${shopId}`)
}
</script>
<style lang="scss" scoped>
.table-con {
  position: relative;
}

:deep(.export-load) {
  top: -50% !important;
}
:deep(.el-table__fixed-right::before) {
  z-index: 0;
}
</style>
